package com.ykdl.app.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class DownloadAPK extends Service {
	private static final int NOTIFY_ID = 0;
	private DownloadBinder binder;
	private NotificationManager notificationManager;
	private NotificationCompat.Builder notificationBuilder = null;
	private Thread downLoadThread;
	private int progress = 0;
	private String filename;
	private File file;
	String apk_url = null;
	private String filepath = null;
	int startId;
	private final static int START_DOWN = 0x001;
	private final static int UPDATE_PROGRESS = 0x002;
	private final static int DOWN_SUCCESS = 0x003;
	private final static int DOWN_ERROR = 0x004;
	private final static int CANNECL_DOWN = 0x0088;
	
	private final static int MAX_BUFFER = 4840;
	private boolean canceled = false;
	private boolean isDownLoading = true;
	
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		binder = new DownloadBinder();
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		 this.startId = startId;
		return super.onStartCommand(intent, flags, startId);
	}

	public class DownloadBinder extends Binder {
		
		public void start(String url) {
			apk_url = url;
			if (downLoadThread == null || !downLoadThread.isAlive()) {
				mHandler.sendEmptyMessage(START_DOWN);
				new Thread() {
					public void run() {
						// 下载
						downLoadThread = new Thread(mdownApkRunnable);
						downLoadThread.start();
					};
				}.start();
			}
		}
		
		public void cancel() {
			canceled = true;
			
		}
		public boolean isCanceled() {
			return canceled;
		}
		public boolean isDownLoading(){
			return isDownLoading;
		}
	}
	
	
	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(apk_url);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();
				if(filename == null){
				        filename = apk_url.substring(apk_url.lastIndexOf("/") + 1,apk_url.length());
				}
				
				filepath =FileUtil.setFilePath(DownloadAPK.this);
				file = new File(filepath + filename);
				FileOutputStream fos = new FileOutputStream(file);
				
				int count = 0;
				int lastRate = 0;
				byte[]  buf = new byte[MAX_BUFFER];
				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					if (progress >= lastRate + 1) {
						//更新进度
						updateProgress();
						lastRate = progress;
					}
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_SUCCESS);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!canceled);// 点击取消就停止下载.

				fos.flush();
				fos.close();
				is.close();
				
				if(canceled){//取消下载服务,删除不完整的文件
					mHandler.sendEmptyMessage(CANNECL_DOWN);
					file.delete();
				}
			} catch (MalformedURLException e) {
				mHandler.sendMessage(mHandler.obtainMessage(DOWN_ERROR, e));
			} catch (IOException e) {
				mHandler.sendMessage(mHandler.obtainMessage(DOWN_ERROR, e));
			}catch(Exception e){
				mHandler.sendMessage(mHandler.obtainMessage(DOWN_ERROR, e));
			}

		}

	};
	
	private void updateProgress() {
		Message msg = mHandler.obtainMessage();
		msg.what = UPDATE_PROGRESS;
		msg.arg1 = progress;
		mHandler.sendMessage(mHandler.obtainMessage(UPDATE_PROGRESS));
	}
	
	public void setUpNotification() {
	            try {
	                PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_NO_CREATE);
	                String contentTitle = apk_url;
	                String contentText = new StringBuffer().append(progress) .append("%").toString();
	                int smallIcon = this.getApplicationInfo().icon;
	                if (notificationManager == null) {
	                    notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
	                }

	                if (notificationBuilder == null) {
	                    notificationBuilder = new NotificationCompat.Builder(this)
	                            .setSmallIcon(smallIcon)
	                            .setContentTitle(contentTitle)
	                            .setContentText(contentText)
	                            .setContentIntent(contentIntent)
	                            .setAutoCancel(true);
	                }
	                notificationBuilder.setContentText(contentText);
	                notificationBuilder.setProgress(100, progress, false);
	                notificationManager.notify(NOTIFY_ID, notificationBuilder.build());
	            } catch (Exception e) {
	                e.printStackTrace();
	                Log.e("can not get the package info", e.getMessage());
	            }
	}

	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case START_DOWN: //开始下载
				setUpNotification();
				break;
			case UPDATE_PROGRESS://更新下载进度
				isDownLoading = true;
				String contentText = new StringBuffer().append(progress) .append("%").toString();
				notificationBuilder.setContentText(contentText);
                notificationBuilder.setProgress(100, progress, false);
                notificationManager.notify(NOTIFY_ID, notificationBuilder.build());
				break;
			case DOWN_SUCCESS://下载成功
				isDownLoading = false;
				notificationManager.cancel(NOTIFY_ID);
				MobileUtils.installApk(DownloadAPK.this, file.getAbsolutePath());
				DownloadAPK.this.stopSelfResult(startId);// 停掉服务自身
				break;
			case DOWN_ERROR://下载错误
				isDownLoading = false;
				DownloadAPK.this.stopSelfResult(startId);// 停掉服务自身
				break;
			case CANNECL_DOWN://手动取消下载任务
				isDownLoading = false;
				notificationManager.cancel(NOTIFY_ID);
			}
		}
	};
}
